﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data;
public partial class shop_Clearing : System.Web.UI.Page
{
    protected int user_id;//会员id
    public Double dTotal = 0.00; //总计款额
    public int QTotal = 0; //总计数量
    public int dintegral;//所得总积分
    public Double user_money = 0.00;//会员账户余额
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Cms.Model.C_user userModel = adminUser.GetuserLoginState();
            this.user_id = userModel.id;
            Bind_date(user_id);//收货地址赋值
            Bind_date_cart(user_id);//购物车赋值
            bind_coupon();//绑定优惠卷和现金卷
            user_money = Convert.ToDouble(new Cms.BLL.C_user().GetModel(user_id).userMoney);//获取会员账户余额
        }
    }

    #region 收货地址赋值=======================
    /// <summary>
    /// 收货地址赋值
    /// </summary>
    /// <param name="user_id"></param>
    public void Bind_date(int user_id)
    {
        DataSet ds = new Cms.BLL.c_user_address().GetList(1, "is_default=1 and user_id=" + user_id, "id desc");
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            RepAddress.DataSource = ds.Tables[0].DefaultView;
            RepAddress.DataBind();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {

                addressId.Value = ds.Tables[0].Rows[i]["id"].ToString();
            }
        }
        else
        {
            JscriptMsg("请添加收货地址！", "/shop/EditAddress.aspx?action=add&ReturnPage=/shop/Clearing.aspx", "Error");
        }

    }
    #endregion

    #region 购物车赋值操作==================================
    /// <summary>
    /// 购物车赋值
    /// </summary>
    public void Bind_date_cart(int user_id)
    {

        DataSet ds = new Cms.BLL.C_user_cart().GetList("is_checked=2 and user_id=" + user_id);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            RepList.DataSource = ds.Tables[0].DefaultView;
            RepList.DataBind();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dTotal += Convert.ToDouble(ds.Tables[0].Rows[i]["price"]) * Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]);
                QTotal += Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]);
                dintegral += Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]) * Convert.ToInt32(ds.Tables[0].Rows[i]["integral"].ToString() == "" ? "0" : ds.Tables[0].Rows[i]["integral"].ToString());
            }
        }
        else
        {
            RepList.DataSource = ds.Tables[0].DefaultView;
            RepList.DataBind();
        }
        price_sum.Value = dTotal.ToString("0.00");
        quantity_sum.Value = QTotal.ToString(); ;
        integral_sum.Value = dintegral.ToString();
    }
    /// <summary>
    /// 获取产品封面图
    /// </summary>
    /// <param name="article_id"></param>
    /// <returns></returns>
    public string getPhoto(string article_id)
    {
        string result = "";
        if (new Cms.BLL.C_article().Exists(Convert.ToInt32(article_id)))
        {
            result = new Cms.BLL.C_article().GetModel(Convert.ToInt32(article_id)).photoUrl.ToString();
        }
        return result;
    }
    /// <summary>
    /// 加减数量
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    protected void RepList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int id = Convert.ToInt32(((HiddenField)e.Item.FindControl("Fielddocid")).Value);
        switch (e.CommandName)
        {
            case "lbtnAdd":
                update(id, "+");
                break;
            case "lbtnLess":
                update(id, "-");
                break;
        }
    }


    protected void RepList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {


    }


    /// <summary>
    /// 加减数量
    /// </summary>
    /// <param name="id"></param>
    public void update(int id, string action)
    {

        if (new Cms.BLL.C_user_cart().GetModel(id).quantity != 1 || action != "-")
        {
            int count = Cms.DBUtility.DbHelperSQL.ExecuteSql("update c_user_cart set quantity=quantity" + action + "1 where id=" + id);
        }
        //重新绑定
        Cms.Model.C_user userModel = adminUser.GetuserLoginState();
        this.user_id = userModel.id;
        Bind_date(user_id);//数据赋值
    }


    #endregion

    #region 绑定优惠卷和现金卷===========
    public void bind_coupon()
    {
        Cms.Model.C_user userModel = adminUser.GetuserLoginState();
        DataTable dt = new Cms.BLL.C_user_coupon().GetList("user_id=" + userModel.id + "and type_id=123").Tables[0];
        if (dt != null && dt.Rows.Count > 0)
        {
            DropDownList1.Items.Clear();
            DropDownList1.Items.Add(new ListItem("请选择优惠卷", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                ListItem item = new ListItem();
                item.Text = dr["title"].ToString();
                item.Value = dr["id"].ToString();
                DropDownList1.Items.Add(item);
            }
        }
        else
        {
            DropDownList1.Items.Clear();
            DropDownList1.Items.Add(new ListItem("暂无优惠卷", "0"));
        }

        dt = new Cms.BLL.C_user_coupon().GetList("user_id=" + userModel.id + "and type_id=124").Tables[0];
        if (dt != null && dt.Rows.Count > 0)
        {
            DropDownList2.Items.Clear();
            DropDownList2.Items.Add(new ListItem("请选择现金卷", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                ListItem item = new ListItem();
                item.Text = dr["title"].ToString();
                item.Value = dr["id"].ToString();
                DropDownList2.Items.Add(item);
            }
        }
        else
        {
            DropDownList2.Items.Clear();
            DropDownList2.Items.Add(new ListItem("暂无现金卷", "0"));
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList2.SelectedValue == "0")
        {
            decimal dPrice1 = Convert.ToDecimal("0");
            if (DropDownList1.SelectedValue != "0")
            {
                dPrice1 = Convert.ToDecimal(new Cms.BLL.C_user_coupon().GetModel(Convert.ToInt32(DropDownList1.SelectedValue)).price);

                decimal sum_price = Convert.ToDecimal(price_sum.Value);
                if (sum_price <= dPrice1)
                {
                    DropDownList1.SelectedValue = "0";
                    JscriptMsg("很遗憾，订单总额不能小于优惠卷面值！", "NotJump", "Error");
                }
                else
                {
                    sum_price = sum_price - dPrice1;
                    price_sum.Value = sum_price.ToString("0.00");
                    dTotal = Convert.ToDouble(sum_price);
                }
            }
            else
            {
                Cms.Model.C_user userModel = adminUser.GetuserLoginState();
                this.user_id = userModel.id;
                DataSet ds = new Cms.BLL.C_user_cart().GetList("is_checked=2 and user_id=" + user_id);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dTotal += Convert.ToDouble(ds.Tables[0].Rows[i]["price"]) * Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]);
                        QTotal += Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]);
                        dintegral += Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]) * Convert.ToInt32(ds.Tables[0].Rows[i]["integral"].ToString() == "" ? "0" : ds.Tables[0].Rows[i]["integral"].ToString());
                    }
                }
                price_sum.Value = dTotal.ToString("0.00");
            }
        }
        else
        {
            DropDownList1.SelectedValue = "0";
            price_sum.Value = Convert.ToDecimal(price_sum.Value).ToString("0.00");
            dTotal = Convert.ToDouble(Convert.ToDecimal(price_sum.Value));
            JscriptMsg("很遗憾，只能选择一种卷！", "NotJump", "Error");
        }

    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedValue == "0")
        {
            decimal dPrice2 = Convert.ToDecimal("0");
            if (DropDownList2.SelectedValue != "0")
            {
                dPrice2 = Convert.ToDecimal(new Cms.BLL.C_user_coupon().GetModel(Convert.ToInt32(DropDownList2.SelectedValue)).price);

                decimal sum_price = Convert.ToDecimal(price_sum.Value);
                if (sum_price <= dPrice2)
                {
                    DropDownList2.SelectedValue = "0";
                    JscriptMsg("很遗憾，订单总额不能小于现金卷面值！", "NotJump", "Error");
                }
                else
                {
                    sum_price = sum_price - dPrice2;
                    price_sum.Value = sum_price.ToString("0.00");
                    dTotal = Convert.ToDouble(sum_price);
                }
            }
            else
            {
                Cms.Model.C_user userModel = adminUser.GetuserLoginState();
                this.user_id = userModel.id;
                DataSet ds = new Cms.BLL.C_user_cart().GetList("is_checked=2 and user_id=" + user_id);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dTotal += Convert.ToDouble(ds.Tables[0].Rows[i]["price"]) * Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]);
                        QTotal += Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]);
                        dintegral += Convert.ToInt32(ds.Tables[0].Rows[i]["quantity"]) * Convert.ToInt32(ds.Tables[0].Rows[i]["integral"].ToString() == "" ? "0" : ds.Tables[0].Rows[i]["integral"].ToString());
                    }
                }
                price_sum.Value = dTotal.ToString("0.00");
            }
        }
        else
        {
            DropDownList2.SelectedValue = "0";
            price_sum.Value = Convert.ToDecimal(price_sum.Value).ToString("0.00");
            dTotal = Convert.ToDouble(Convert.ToDecimal(price_sum.Value));
            JscriptMsg("很遗憾，只能选择一种卷！", "NotJump", "Error");
        }
    }

    #endregion

    #region 提交订单====================
    protected void Button1_Click(object sender, EventArgs e)
    {
        Cms.BLL.C_order bllOrder = new Cms.BLL.C_order();
        Cms.Model.C_order modelOrder = new Cms.Model.C_order();

        Cms.BLL.C_ordersub bllOrderSub = new Cms.BLL.C_ordersub();
        Cms.Model.C_ordersub modelOrderSub = new Cms.Model.C_ordersub();

        Cms.Model.C_user userModel = adminUser.GetuserLoginState();
        this.user_id = userModel.id;

        modelOrder.order_num = Cms.Common.Utils.GetOrderNumber();//生成订单号
        modelOrder.user_id = user_id;
        modelOrder.adress_id = Convert.ToInt32(addressId.Value);//收货地址id
        modelOrder.quantity_sum = Convert.ToInt32(quantity_sum.Value);
        modelOrder.price_sum = Convert.ToDecimal(price_sum.Value);
        modelOrder.integral_sum = Convert.ToInt32(integral_sum.Value);
        modelOrder.is_payment = 0;//0表示未支付
        modelOrder.order_status = 0;//订单状态
        modelOrder.is_delivery = 0;//订单是否发货
        modelOrder.is_receiving = 0;//是否收货
        modelOrder.is_transaction = 0;//订单是否交易完成
        modelOrder.is_sms = 0;//是否发送短信
        if (RadioButton1.Checked)
        {
            modelOrder.pay_method = RadioButton1.Text; ;
        }
        //else if (RadioButton2.Checked)
        //{
        //    modelOrder.pay_method = RadioButton2.Text;
        //}//支付方式

        if (RadioButton3.Checked)
        {
            modelOrder.shipping_method = RadioButton3.Text; ;
        }
        else if (RadioButton4.Checked)
        {
            modelOrder.shipping_method = RadioButton4.Text;
        }//配送方式
        modelOrder.Coupon_id = Convert.ToInt32(DropDownList1.SelectedValue);//优惠卷
        modelOrder.cash_volume_id = Convert.ToInt32(DropDownList2.SelectedValue);//现金卷
        
        //modelOrder.integral_arrived =Convert.ToInt32(integralArrived.Value);//抵用多少积分
        modelOrder.note = note.Value;//留言
        modelOrder.recommended_code = recommended_code.Value;//推荐码
        modelOrder.updateTime = DateTime.Now;
        int result = bllOrder.Add(modelOrder);
        if (result > 0)
        {
            DataTable dt = new Cms.BLL.C_user_cart().GetList("is_checked=2 and user_id=" + user_id).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    modelOrderSub.order_id = result;
                    modelOrderSub.order_num = modelOrder.order_num;
                    modelOrderSub.user_id = user_id;
                    modelOrderSub.article_id = Convert.ToInt32(dt.Rows[i]["article_id"]);
                    modelOrderSub.title = dt.Rows[i]["title"].ToString();
                    modelOrderSub.price = Convert.ToDecimal(dt.Rows[i]["price"].ToString());
                    modelOrderSub.quantity = Convert.ToInt32(dt.Rows[i]["quantity"]);
                    modelOrderSub.integral = Convert.ToInt32(dt.Rows[i]["integral"]);
                    modelOrderSub.property_value = dt.Rows[i]["property_value"].ToString();
                    modelOrderSub.note = dt.Rows[i]["note"].ToString();
                    modelOrderSub.updateTime = modelOrder.updateTime;
                    bllOrderSub.Add(modelOrderSub);
                    new Cms.BLL.C_user_cart().Delete(Convert.ToInt32(dt.Rows[i]["id"]));
                }
            }
            #region 优惠卷现金卷状态改变====
            Cms.BLL.C_user_coupon couponbll = new Cms.BLL.C_user_coupon();
            if(modelOrder.Coupon_id!=0)
            {
                Cms.Model.C_user_coupon couponmodel=couponbll.GetModel(Convert.ToInt32(modelOrder.Coupon_id));
                couponmodel.status = 1;
                couponbll.Update(couponmodel);
            }
            if (modelOrder.cash_volume_id != 0)
            {
                Cms.Model.C_user_coupon couponmodel = couponbll.GetModel(Convert.ToInt32(modelOrder.cash_volume_id));
                couponmodel.status = 1;
                couponbll.Update(couponmodel);
            }
            #endregion

            //JscriptMsg("恭喜您，订单提交成功！", "/shop/myOrder.aspx", "Success");

            //JscriptMsg("恭喜您，订单提交成功！", "/api/payment/paypage.aspx?orderid=" + result, "Success");

            JscriptMsg("恭喜您，订单提交成功！", "/shop/orderDetail.aspx?id=" + result, "Success");
        }
        else
        {
            JscriptMsg("很遗憾，订单提交失败！", "NotJump", "Error");
        }


    }
    #endregion

    #region 提示框=================================
    public void JscriptMsg(string msgtitle, string url, string msgcss)
    {
        string msbox = "";
        if (url == "back")
        {
            msbox = "jsdialog(\"提示\", \"" + msgtitle + "\",\"" + url + "\", \"\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }
        else
        {
            msbox = "jsprintWeb(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }

    }
    #endregion


}